<template>
    <div class="order-list-container">
        <h2>我的订单</h2>

        <div class="view-switcher">
            <el-button :type="currentView === 'buyer' ? 'primary' : ''" @click="switchView('buyer')">买家订单</el-button>
            <el-button :type="currentView === 'seller' ? 'primary' : ''" @click="switchView('seller')">卖家订单</el-button>
        </div>

        <el-table :data="orderList" border style="width: 100%" v-loading="loading">
            <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
            <el-table-column prop="number" label="订单编号" width="180"></el-table-column>
            <el-table-column prop="auctionTitle" label="商品名称" min-width="180"></el-table-column>
            <el-table-column prop="orderAmount" label="成交价格" width="120">
                <template #default="scope">
                    <span class="price">￥{{ scope.row.orderAmount }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="orderStatus" label="订单状态" width="120">
                <template #default="scope">
                    <el-tag :type="getOrderStatusType(scope.row.orderStatus)">
                        {{ getOrderStatusText(scope.row.orderStatus) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="280" align="center">
                <template #default="scope">
                    <el-button type="primary" link @click="viewOrderDetail(scope.row.id)">查看详情</el-button>
                    <template v-if="currentView === 'buyer'">
                        <el-button v-if="scope.row.orderStatus === 0" type="primary" link
                            @click="handlePayOrder(scope.row)">支付</el-button>
                        <el-button v-if="scope.row.orderStatus === 0 || scope.row.orderStatus === 1" type="danger" link
                            @click="handleCancelOrder(scope.row.id)">取消订单</el-button>
                        <el-button v-if="scope.row.orderStatus === 2" type="success" link
                            @click="handleConfirmOrder(scope.row.id)">确认收货</el-button>
                    </template>
                    <template v-else>
                        <el-button v-if="scope.row.orderStatus === 0 || scope.row.orderStatus === 1" type="danger" link
                            @click="handleCancelOrder(scope.row.id)">取消订单</el-button>
                        <el-button v-if="scope.row.orderStatus === 1" type="success" link
                            @click="handleShipOrder(scope.row.id)">发货</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total"></el-pagination>
        </div>

        <!-- 订单详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="订单详情" width="50%" destroy-on-close>
            <el-descriptions :column="1" border>
                <el-descriptions-item label="订单编号">{{ orderDetail.number }}</el-descriptions-item>
                <el-descriptions-item label="商品名称">{{ orderDetail.auctionTitle }}</el-descriptions-item>
                <el-descriptions-item label="商品图片">
                    <el-image style="width: 200px; height: 200px" :src="orderDetail.auctionImage" fit="cover"
                        :preview-src-list="[orderDetail.auctionImage]"></el-image>
                </el-descriptions-item>
                <el-descriptions-item label="成交价格">
                    <span class="price">￥{{ orderDetail.orderAmount }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="订单状态">
                    <el-tag :type="getOrderStatusType(orderDetail.orderStatus)">
                        {{ getOrderStatusText(orderDetail.orderStatus) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="买家">{{ orderDetail.buyerName }}</el-descriptions-item>
                <el-descriptions-item label="卖家">{{ orderDetail.sellerName }}</el-descriptions-item>
                <el-descriptions-item label="收货人信息">
                    <div>姓名：{{ orderDetail.consignee }}</div>
                    <div>电话：{{ orderDetail.phone }}</div>
                    <div>地址：{{ orderDetail.address }}</div>
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ formatDate(orderDetail.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="支付时间" v-if="orderDetail.payTime">{{ formatDate(orderDetail.payTime)
                    }}</el-descriptions-item>
                <el-descriptions-item label="发货时间" v-if="orderDetail.deliveryTime">{{
                    formatDate(orderDetail.deliveryTime)
                    }}</el-descriptions-item>
                <el-descriptions-item label="完成时间" v-if="orderDetail.finishTime">{{ formatDate(orderDetail.finishTime)
                    }}</el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBuyerOrders, getSellerOrders, getOrderDetail, cancelOrder, confirmOrder, shipOrder, payOrder } from '@/api/order'

const router = useRouter()
const loading = ref(false)
const orderList = ref([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const currentView = ref('buyer') // 'buyer' or 'seller'

// 获取订单列表
const fetchOrderList = async () => {
    loading.value = true
    try {
        let res
        if (currentView.value === 'buyer') {
            res = await getBuyerOrders(page.value, pageSize.value)
        } else {
            res = await getSellerOrders(page.value, pageSize.value)
        }

        if (res.code === 1 && res.data) {
            orderList.value = res.data.list || []
            total.value = res.data.total || 0
        } else {
            throw new Error(res.msg || '获取订单列表失败')
        }
    } catch (error) {
        console.error('获取订单列表失败', error)
        ElMessage.error('您还不是卖家，无法查看卖家订单')
    } finally {
        loading.value = false
    }
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
    const statusMap = {
        0: 'warning',   // 待支付
        1: 'success',   // 已支付
        2: 'info',      // 已发货
        3: 'success',   // 已完成
        4: 'danger'     // 已取消
    }
    return statusMap[status] || 'info'
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
    const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已发货',
        3: '已完成',
        4: '已取消'
    }
    return statusMap[status] || '未知状态'
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
    pageSize.value = val
    page.value = 1
    fetchOrderList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
    page.value = val
    fetchOrderList()
}

// 订单详情相关
const detailDialogVisible = ref(false)
const orderDetail = ref({})

// 查看订单详情
const viewOrderDetail = async (orderId) => {
    try {
        const response = await getOrderDetail(orderId)
        if (response.code === 1) {
            orderDetail.value = response.data
            detailDialogVisible.value = true
        } else {
            throw new Error(response.msg || '获取订单详情失败')
        }
    } catch (error) {
        console.error('获取订单详情失败', error)
        ElMessage.error('获取订单详情失败，请稍后再试')
    }
}

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '-'
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    })
}

// 切换订单视图
const switchView = (view) => {
    currentView.value = view
    page.value = 1 // Reset page when switching view
    fetchOrderList()
}

// 取消订单
const handleCancelOrder = async (orderId) => {
    try {
        await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        const response = await cancelOrder(orderId)
        if (response.code === 1) {
            ElMessage.success('订单取消成功')
            fetchOrderList()
        } else {
            throw new Error(response.msg || '取消订单失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('取消订单失败', error)
            ElMessage.error(error.message || '取消订单失败，请稍后再试')
        }
    }
}

// 确认收货
const handleConfirmOrder = async (orderId) => {
    try {
        await ElMessageBox.confirm('确定要确认收货吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        const response = await confirmOrder(orderId)
        if (response.code === 1) {
            ElMessage.success('确认收货成功')
            fetchOrderList()
        } else {
            throw new Error(response.msg || '确认收货失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('确认收货失败', error)
            ElMessage.error(error.message || '确认收货失败，请稍后再试')
        }
    }
}

// 发货
const handleShipOrder = async (orderId) => {
    try {
        const { value: trackingNumber } = await ElMessageBox.prompt('请输入物流单号', '发货', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[a-zA-Z0-9]+$/,
            inputErrorMessage: '物流单号只能包含字母和数字'
        })

        if (trackingNumber) {
            const response = await shipOrder(orderId, trackingNumber)
            if (response.code === 1) {
                ElMessage.success('发货成功')
                fetchOrderList()
            } else {
                throw new Error(response.msg || '发货失败')
            }
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('发货失败', error)
            ElMessage.error(error.message || '发货失败，请稍后再试')
        }
    }
}

// 支付订单
const handlePayOrder = async (order) => {
    try {
        await ElMessageBox.confirm(
            `确定要支付该订单吗？\n订单金额：￥${order.orderAmount}`,
            '支付确认',
            {
                confirmButtonText: '确定支付',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        const response = await payOrder(order.id)
        if (response.code === 1) {
            ElMessage.success('支付成功')
            fetchOrderList()
        } else {
            throw new Error(response.msg || '支付失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('支付失败', error)
            ElMessage.error(error.message || '支付失败，请稍后再试')
        }
    }
}

// 页面初始化时获取订单列表
onMounted(() => {
    fetchOrderList()
})
</script>

<style scoped>
.order-list-container {
    padding: 20px;
}

.price {
    color: #f56c6c;
    font-weight: bold;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

.view-switcher {
    margin-bottom: 20px;
}

.dialog-footer {
    text-align: right;
    margin-top: 20px;
}
</style>